﻿<h1>Channels in Go</h1>

<p>
Channel is an important built-in feature in Go.
It is one of the features that makes Go unique.
Along with another unique feature,
<a href="control-flows-more.html#goroutine">goroutine</a>,
channel makes concurrent programming convenient, fun and
lowers the difficulties of concurrent programming.
</p>

<p>
Channel mainly acts as a <a href="control-flows-more.html#synchronization">concurrency synchronization</a> technique.
This article will list all the channel related concepts, syntax and rules.
To understand channels better, the internal structure of channels and some
implementation details by the standard Go compiler/runtime are also simply described.
</p>

<p>
The information in this article may be slightly challenging for new gophers.
Some parts of this article may need to be read several times to be fully understood.
</p>

<h3>Channel Introduction</h3>

<p>
One suggestion (made by <i>Rob Pike</i>) for concurrent programming is
<b>don't (let computations) communicate by sharing memory,
(let them) share memory by communicating (through channels)</b>.
(We can view each computation as a goroutine in Go programming.)
</p>

<p>
Communicating by sharing memory and sharing memory by communicating
are two programming manners in concurrent programming.
When goroutines communicate by sharing memory, we use
traditional concurrency synchronization techniques, such as mutex locks,
to protect the shared memory to prevent data races.
We can use channels to implement sharing memory by communicating.
</p>

<p>
Go provides a unique concurrency synchronization technique, channel.
Channels make goroutines share memory by communicating.
We can view a channel as an internal FIFO (first in, first out) queue
within a program. Some goroutines send values to the queue (the channel)
and some other goroutines receive values from the queue.
</p>

<p>
Along with transferring values (through channels),
the ownership of some values may also be transferred between goroutines.
When a goroutine sends a value to a channel,
we can view the goroutine releases the ownership of some values.
When a goroutine receives a value from a channel,
we can view the goroutine acquires the ownerships of some values.
</p>

<p>
Surely, there may be also not any ownership transferred
along with channel communications.
</p>

<p>
The values (whose ownerships are transferred) are often referenced
(but are not required to be referenced) by the transferred value.
Please note, here, when we talk about ownership,
we mean the ownership from the logic view.
Unlike Rust language, Go doesn't ensure value ownership from the syntax level.
Go channels can help programmers write data races free code easily,
but Go channels can't prevent programmers from
writing bad concurrent code from the syntax level.
</p>

<p>
Although Go also supports traditional concurrency synchronization techniques.
only channel is first-class citizen in Go. Channel is one kind of types in Go,
so we can use channels without importing any packages.
On the other hand, those traditional concurrency synchronization techniques are provided
in the <code>sync</code> and <code>sync/atomic</code> standard packages.
</p>

<p>
Honestly, each concurrency synchronization technique
has its own best use scenarios.
But channel has <a href="channel-use-cases.html">a wider application range
and has more variety in using</a>.
One problem of channels is, the experience of programming with channels is
so enjoyable and fun that programmers often even prefer to use channels for
the scenarios which channels are not best for.
</p>

<h3>Channel Types and Values</h3>

<div>
<p>
Like array, slice and map, each channel type has an element type.
A channel can only transfer values of the element type of the channel.
</p>

Channel types can be bi-directional or single-directional.
Assume <code>T</code> is an arbitrary type,
<ul>
<li>
	<code>chan T</code> denotes a bidirectional channel type.
	Compilers allow both receiving values from and sending values to
	bidirectional channels.
</li>
<li>
	<code>chan&lt;- T</code> denotes a send-only channel type.
	Compilers don't allow receiving values from send-only channels.
</li>
<li>
	<code>&lt;-chan T</code> denotes a receive-only channel type.
	Compilers don't allow sending values to receive-only channels.
</li>
</ul>

<p>
<code>T</code> is called element types of these channel types.
</p>

<p>
Values of bidirectional channel type <code>chan T</code> can be implicitly converted to
both send-only type <code>chan&lt;- T</code> and
receive-only type <code>&lt;-chan T</code>, but not vice versa (even if explicitly).
Values of send-only type <code>chan&lt;- T</code> can't be converted to
receive-only type <code>&lt;-chan T</code>, and vice versa.
Note that the <code>&lt;-</code> signs in channel type literals are modifiers.
</p>

<p>
Each channel value has a capacity, which will be explained in the section after next.
A channel value with a zero capacity is called unbuffered channel and
a channel value with a non-zero capacity is called buffered channel.
</p>

<p>
The zero values of channel types are represented with
the predeclared identifier <code>nil</code>.
A non-nil channel value must be created by using the built-in <code>make</code>
function. For example, <code>make(chan int, 10)</code> will create a channel
whose element type is <code>int</code>.
The second argument of the <code>make</code> function call specifies
the capacity of the new created channel.
The second parameter is optional and its default value is zero.
</p>

</div>

<a class="anchor" id="assign-and-compare"></a>
<h3>Channel Value Comparisons</h3>

<p>
All channel types are comparable types.
</p>

<p>
From the article <a href="value-part.html">value parts</a>,
we know that non-nil channel values are multi-part values.
If one channel value is assigned to another,
the two channels share the same underlying part(s).
In other words, those two channels represent the same internal channel object.
The result of comparing them is <code>true</code>.
</p>

<a class="anchor" id="operations"></a>
<h3>Channel Operations</h3>

<div>
<p>
There are five channel specified operations.
Assume the channel is <code>ch</code>,
their syntax and function calls of these operations are listed here.
</p>
<ol>
<li>
	Close the channel by using the following function call
<pre class="disable-line-numbers111"><code class="language-go">close(ch)
</code></pre>
	<p>
	where <code>close</code> is a built-in function.
	The argument of a <code>close</code> function call must be a channel value,
	and the channel <code>ch</code> must not be a receive-only channel.
	</p>
</li>
<li>
	Send a value, <code>v</code>, to the channel
	by using the following syntax
<pre class="disable-line-numbers111"><code class="language-go">ch &lt;- v
</code></pre>
	<p>
	where <code>v</code> must be a value which is assignable to
	the element type of channel <code>ch</code>,
	and the channel <code>ch</code> must not be a receive-only channel.
	Note that here <code>&lt;-</code> is a channel-send operator.
	</p>
</li>
<li>
	Receive a value from the channel by using the following syntax
<pre class="disable-line-numbers111"><code class="language-go">&lt;-ch
</code></pre>
	A channel receive operation always returns at least one result,
	which is a value of the element type of the channel,
	and the channel <code>ch</code> must not be a send-only channel.
	Note that here <code>&lt;-</code> is a channel-receive operator.
	Yes, its representation is the same as a channel-send operator.

	<p>
	</p>

	For most scenarios, a channel receive operation is viewed as
	a single-value expression.
	However, when a channel operation is used as the only source value
	expression in an assignment, it can result a second optional
	untyped boolean value and become a multi-value expression.
	The untyped boolean value indicates whether or not
	the first result is sent before the channel is closed.
	(Below we will learn that we can receive unlimited number of values
	from a closed channel.)

	<p>
	</p>
	Two channel receive operations which are used as source values in assignments:
<pre class="disable-line-numbers111"><code class="language-go">v = &lt;-ch
v, sentBeforeClosed = &lt;-ch
</code></pre>
</li>
<li>
	Query the value buffer capacity of the channel
	by using the following function call
<pre class="disable-line-numbers111"><code class="language-go">cap(ch)
</code></pre>
	<p>
	where <code>cap</code> is a built-in function which has ever been
	introduced in <a href="container.html#cap-len">containers in Go</a>.
	The return result of a <code>cap</code> function call
	is an <code>int</code> value.
	</p>
</li>
<li>
	Query the current number of values in the value buffer
	(or the length)
	of the channel by using the following function call
<pre class="disable-line-numbers111"><code class="language-go">len(ch)
</code></pre>
	<p>
	where <code>len</code> is a built-in function
	which also has ever been introduced before.
	The return value of a <code>len</code> function call
	is an <code>int</code> value.
	The result length is number of elements which have already
	been sent successfully to the queried channel
	but haven't been received (taken out) yet.
	</p>
</li>
</ol>

<p>
Most basic operations in Go are not synchronized.
In other words, they are not concurrency-safe.
These operations include value assignments, argument passing and
container element manipulations, etc.
However, all the just introduced channel operations are already synchronized,
so no further synchronizations are needed to safely perform these operations,
except the case of concurrent send and close operations on the channel.
The exception case should be avoided in code design, for it is a bad design.
(The reason will be explained below.)
</p>

<!--
https://github.com/golang/go/issues/30372
https://github.com/golang/go/issues/27769
-->

<p>
Like most other operations in Go,
channel value assignments are not synchronized.
Similarly, assigning the received value to another value is also
not synchronized, though any channel receive operation is synchronized.
</p>

<p>
If the queried channel is a nil channel, both of the
built-in <code>cap</code> and <code>len</code> functions return zero.
The two query operations are so simple that
they will not get further explanations later.
In fact, the two operations are seldom used in practice.
</p>

<p>
Channel send, receive and close operations will be explained in detail in the next section.
</p>

</div>

<a class="anchor" id="channel-operation-explanations"></a>
<h3>Detailed Explanations for Channel Operations</h3>

<div>
To make the explanations for channel operations simple and clear,
in the remaining of this article,
channels will be classified into three categories:
<ol>
<li>
	nil channels.
</li>
<li>
	non-nil but closed channels.
</li>
<li>
	not-closed non-nil channels.
</li>
</ol>

<p>
The following table simply summarizes the behaviors for all kinds of operations
applying on nil, closed and not-closed non-nil channels.
</p>

<table border="1" class="table table-bordered text-center" style="width: auto !important;">
<thead>
	<tr class="active">
	<th class="text-center" valign="bottom" align="center">Operation</th>
	<th class="text-center" valign="bottom" align="center">A Nil Channel</th>
	<th class="text-center" valign="bottom" align="center">A Closed Channel</th>
	<th class="text-center" valign="bottom" align="center">A Not-Closed Non-Nil Channel</th>
	</tr>
</thead>
<tbody>
	<tr>
	<th scope="row" class="text-center">Close</th>
	<td style="vertical-align: middle;" valign="middle" align="center">panic</td>
	<td style="vertical-align: middle;" valign="middle" align="center">panic</td>
	<td style="vertical-align: middle;" valign="middle" align="center">succeed to close <sup>(C)</sup></td>
	</tr>
	<tr>
	<th scope="row" class="text-center" valign="middle" align="center">Send Value To</th>
	<td style="vertical-align: middle;" valign="middle" align="center">block for ever</td>
	<td style="vertical-align: middle;" valign="middle" align="center">panic</td>
	<td style="vertical-align: middle;" valign="middle" align="center">block or succeed to send <sup>(B)</sup></td>
	</tr>
	<tr>
	<th scope="row" class="text-center" valign="middle" align="center">Receive Value From</th>
	<td style="vertical-align: middle;" valign="middle" align="center">block for ever</td>
	<td style="vertical-align: middle;" valign="middle" align="center">never block <sup>(D)</sup></td>
	<td style="vertical-align: middle;" valign="middle" align="center">block or succeed to receive <sup>(A)</sup></td>
	</tr>
</tbody>
</table>

For the five cases shown without superscripts, the behaviors are very clear.
<ul>
<li>
	Closing a nil or an already closed channel
	produces a panic in the current goroutine.
</li>
<li>
	Sending a value to a closed channel also
	produces a panic in the current goroutine.
</li>
<li>
	Sending a value to or receiving a value from a nil channel makes
	the current goroutine enter and stay in blocking state for ever.
</li>
</ul>

<p>
The following will make more explanations for the four cases shown with superscripts (A, B, C and D).
</p>

<p>
To better understand channel types and values, and to make some explanations
easier, looking in the raw internal structures of internal channel objects
is very helpful.
</p>

We can think of each channel consisting of three queues (all can be viewed as FIFO queues) internally:
<ol>
<li>
	the receiving goroutine queue.
	The queue is a linked list without size limitation.
	Goroutines in this queue are all in blocking state and waiting to receive values from that channel.
	<!-- not true
	The addresses of the values which are prepared to store the received
	values are also stored in the queue along with each goroutine.
	-->
</li>
<li>
	the sending goroutine queue.
	The queue is also a linked list without size limitation.
	Goroutines in this queue are all in blocking state and waiting to send values to that channel.
	The value (or the address of the value, depending on compiler implementation)
	each goroutine is trying to send is also stored in the queue along with that goroutine.
</li>
<li>
	the value buffer queue. This is a circular queue.
	Its size is equal to the capacity of the channel.
	The types of the values stored in this buffer queue are all the element type of that channel.
	If the current number of values stored in the value buffer queue of the channel
	reaches the capacity of the channel, the channel is called in full status.
	If no values are stored in the value buffer queue of the channel currently,
	the channel is called in empty status.
	For a zero-capacity (unbuffered) channel, it is always in both full and empty status.
</li>
</ol>

<p>
Each channel internally holds a mutex lock which is used to avoid data races in all kinds of operations.
</p>

<u><b>Channel operation case A</b>:
when a goroutine <code>Gr</code> tries to receive a value from a not-closed non-nil channel</u>,
the goroutine <code>Gr</code> will acquire the lock associated with the channel firstly,
then do the following steps until one condition is satisfied.
<ol>
<li>
	If the value buffer queue of the channel is not empty, in which
	case the receiving goroutine queue of the channel must be empty,
	the goroutine <code>Gr</code> will receive (by unshifting) a value
	from the value buffer queue.
	If the sending goroutine queue of the channel is also not empty,
	a sending goroutine will be unshifted out of the sending goroutine queue
	and resumed to running state again.
	The value the just unshifted sending goroutine trying to send
	will be pushed into the value buffer queue of the channel.
	The receiving goroutine <code>Gr</code> continues running.
	For this scenario, the channel receive operation
	is called a <b>non-blocking operation</b>.
</li>
<li>
	Otherwise (the value buffer queue of the channel is empty),
	if the sending goroutine queue of the channel is not empty,
	in which case the channel must be an unbuffered channel,
	the receiving goroutine <code>Gr</code> will unshift a sending goroutine from the
	sending goroutine queue of the channel and receive the value
	the just unshifted sending goroutine trying to send.
	The just unshifted sending goroutine will get unblocked
	and resumed to running state again.
	The receiving goroutine <code>Gr</code> continues running.
	For this scenario, the channel receive operation
	is called a <b>non-blocking operation</b>.
</li>
<li>
	If value buffer queue and the sending goroutine queue
	of the channel are both empty,
	the goroutine <code>Gr</code> will be pushed into the receiving goroutine queue
	of the channel and enter (and stay in) blocking state.
	It may be resumed to running state when another goroutine
	sends a value to the channel later.
	For this scenario, the channel receive operation
	is called a <b>blocking operation</b>.
</li>
</ol>

<u><b>Channel rule case B</b>:
when a goroutine <code>Gs</code> tries to send a value to a not-closed non-nil channel</u>,
the goroutine <code>Gs</code> will acquire the lock associated with the channel firstly,
then do the following steps until one step condition is satisfied.
<ol>
<li>
	If the receiving goroutine queue of the channel is not empty,
	in which case the value buffer queue of the channel must be empty,
	the sending goroutine <code>Gs</code> will unshift a receiving goroutine
	from the receiving goroutine queue of the channel
	and send the value to the just unshifted receiving goroutine.
	The just unshifted receiving goroutine will get unblocked
	and resumed to running state again.
	The sending goroutine <code>Gs</code> continues running.
	For this scenario, the channel send operation
	is called a <b>non-blocking operation</b>.
</li>
<li>
	Otherwise (the receiving goroutine queue is empty),
	if the value buffer queue of the channel is not full,
	in which case the sending goroutine queue must be also empty,
	the value the sending goroutine <code>Gs</code> trying to send will be pushed into
	the value buffer queue, and the sending goroutine <code>Gs</code> continues running.
	For this scenario, the channel send operation
	is called a <b>non-blocking operation</b>.
</li>
<li>
	If the receiving goroutine queue is empty
	and the value buffer queue of the channel is already full,
	the sending goroutine <code>Gs</code> will be pushed into the sending goroutine queue
	of the channel and enter (and stay in) blocking state.
	It may be resumed to running state when another goroutine
	receives a value from the channel later.
	For this scenario, the channel send operation
	is called a <b>blocking operation</b>.
</li>
</ol>

<p>
Above has mentioned, once a non-nil channel is closed, sending a value to the channel will
produce a runtime panic in the current goroutine.
Note, sending data to a closed channel is viewed as a <b>non-blocking operation</b>.
</p>

<u><b>Channel operation case C</b>:
when a goroutine tries to close a not-closed non-nil channel</u>,
once the goroutine has acquired the lock of the channel,
both of the following two steps will be performed by the following order.
<ol>
<li>
	If the receiving goroutine queue of the channel is not empty,
	in which case the value buffer of the channel must be empty,
	all the goroutines in the receiving goroutine queue of
	the channel will be unshifted one by one, each of them will
	receive a zero value of the element type of the channel and be resumed to running state.
</li>
<li>
	If the sending goroutine queue of the channel is not empty,
	all the goroutines in the sending goroutine queue of the channel
	will be unshifted one by one and
	each of them will produce a panic for sending on a closed channel.
	This is the reason why we should avoid concurrent send and close operations on the same channel.
	In fact, data races happen in concurrent send and close operations.
</li>
</ol>

<p>
Note: after a channel is closed, the values which have been already pushed into
the value buffer of the channel are still there.
Please read the closely following explanations for case D for details.
</p>

<p>
<u><b>Channel operation case D</b>:
after a non-nil channel is closed,
channel receive operations on the channel will never block</u>.
The values in the value buffer of the channel can still be received.
The accompanying second optional bool return values are still <code>true</code>.
Once all the values in the value buffer are taken out and received,
infinite zero values of the element type of the channel will be received
by any of the following receive operations on the channel.
As mentioned above,
the optional second return result of a channel receive operation is an untyped boolean
value which indicates whether or not the first result (the received value)
is sent before the channel is closed.
If the second return result is <code>false</code>,
then the first return result (the received value) must be a zero value of the element type of the channel.
</p>

<p>
Knowing what are blocking and non-blocking channel send or receive operations
is important to understand the mechanism of <code>select</code> control flow
blocks which will be introduced in a later section.
</p>

<p>
In the above explanations, if a goroutine is unshifted out of a queue
(either the sending or the receiving goroutine queue) of a channel,
and the goroutine was blocked for being pushed into the queue at a
<a href="#select"><code>select</code> control flow code block</a>,
then the goroutine will be resumed to running state at step <i>9</i> of the
<a href="#select-implementation"><code>select</code> control flow code block execution</a>.
It may be dequeued from the corresponding goroutine queue of
several channels involved in the <code>select</code> control flow code block.
</p>

According to the explanations listed above, we can get some facts about the internal queues of a channel.
<ul>
<li>
	If the channel is closed,
	both of its sending goroutine queue and receiving goroutine queue must be empty,
	but its value buffer queue may not be empty.
</li>
<li>
	At any time, if the value buffer is not empty,
	then its receiving goroutine queue must be empty.
</li>
<li>
	At any time, if the value buffer is not full,
	then its sending goroutine queue must be empty.
</li>
<li>
	If the channel is buffered, then at any time,
	one of its sending goroutine queue and receiving goroutine queue must be empty.
</li>
<li>
	If the channel is unbuffered, then at any time, generally
	one of its sending goroutine queue and the receiving goroutine queue must be empty,
	but with an exception that a goroutine may be pushed into both of
	the two queues when executing a
	<a href="#select"><code>select</code> control flow code block</a>.
</li>
</ul>
</div>

<h3>Some Channel Use Examples</h3>

<div>
<p>
Let's view some examples which use channels to enhance the understanding by reading the last section.
</p>

A simple request/response example.
The two goroutines in this example talk to each other
through an unbuffered channel.
<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"time"
)

func main() {
	c := make(chan int) // an unbuffered channel
	go func(ch chan<- int, x int) {
		time.Sleep(time.Second)
		// <-ch    // fails to compile
		// Send the value and block until the result is received.
		ch <- x*x // 9 is sent
	}(c, 3)
	done := make(chan struct{})
	go func(ch <-chan int) {
		// Block until 9 is received.
		n := <-ch
		fmt.Println(n) // 9
		// ch <- 123   // fails to compile
		time.Sleep(time.Second)
		done <- struct{}{}
	}(c)
	// Block here until a value is received by
	// the channel "done".
	<-done
	fmt.Println("bye")
}
</code></pre>

<p>
</p>

The output:
<pre class="output"><code>9
bye
</code></pre>

<p>
</p>

A demo of using a buffered channel.
This program is not a concurrent one, it just shows how to use buffered channels.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	c := make(chan int, 2) // a buffered channel
	c <- 3
	c <- 5
	close(c)
	fmt.Println(len(c), cap(c)) // 2 2
	x, ok := <-c
	fmt.Println(x, ok) // 3 true
	fmt.Println(len(c), cap(c)) // 1 2
	x, ok = <-c
	fmt.Println(x, ok) // 5 true
	fmt.Println(len(c), cap(c)) // 0 2
	x, ok = <-c
	fmt.Println(x, ok) // 0 false
	x, ok = <-c
	fmt.Println(x, ok) // 0 false
	fmt.Println(len(c), cap(c)) // 0 2
	close(c) // panic!
	// The send will also panic if the above
	// close call is removed.
	c <- 7
}
</code></pre>

<p>
</p>

A never-ending football game.

<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"time"
)

func main() {
	var ball = make(chan string)
	kickBall := func(playerName string) {
		for {
			fmt.Println(<-ball, "kicked the ball.")
			time.Sleep(time.Second)
			ball <- playerName
		}
	}
	go kickBall("John")
	go kickBall("Alice")
	go kickBall("Bob")
	go kickBall("Emily")
	ball <- "referee" // kick off
	var c chan bool   // nil
	<-c               // blocking here for ever
}
</code></pre>

<p>
</p>

<p>
Please read <a href="channel-use-cases.html">channel use cases</a>
for more channel use examples.
</p>

</div>

<h3>Channel Element Values Are Transferred by Copy</h3>

<p>
When a value is transferred from one goroutine to another goroutine,
the value will be copied at least one time.
If the transferred value ever stayed in the value buffer of a channel,
then two copies will happen in the transfer process.
One copy happens when the value is copied from the sender goroutine into the value buffer,
the other happens when the value is copied from the value buffer to the receiver goroutine.
Like value assignments and function argument passing,
when a value is transferred, <a href="value-part.html#about-value-copy">only
its direct part is copied</a>.
</p>

<p>
For the standard Go compiler,
the size of channel element types must be smaller than <code>65536</code>.
However, generally, we shouldn't create channels with large-size element types,
to avoid too large copy cost in the process of transferring values between goroutines.
So if the passed value size is too large,
it is best to use a pointer element type instead,
to avoid a large value copy cost.
</p>

<h3>About Channel and Goroutine Garbage Collections</h3>

<p>
Note, a channel is referenced by all the goroutines in either
the sending or the receiving goroutine queue of the channel,
so if neither of the queues of the channel is empty,
the channel will not be garbage collected for sure.
On the other hand, if a goroutine is blocked and stays in either
the sending or the receiving goroutine queue of a channel,
then the goroutine will also not be garbage collected for sure,
even if the channel is referenced only by this goroutine.
In fact, a goroutine can be only garbage collected when it has already exited.
</p>

<h3>Channel Send and Receive Operations Are Simple Statements</h3>

<div>
<p>
Channel send operations and receive operations are
<a href="expressions-and-statements.html#simple-statements">simple statements</a>.
A channel receive operation can be always used as a single-value expression.
Simple statements and expressions can be used at certain portions of
<a href="control-flows.html">basic control flow blocks</a>.
</p>

An example in which channel send and receive operations
appear as simple statements in two <code>for</code> control flow blocks.

<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"time"
)

func main() {
	fibonacci := func() chan uint64 {
		c := make(chan uint64)
		go func() {
			var x, y uint64 = 0, 1
			for ; y < (1 << 63); c <- y { // here
				x, y = y, x+y
			}
			close(c)
		}()
		return c
	}
	c := fibonacci()
	for x, ok := <-c; ok; x, ok = <-c { // here
		time.Sleep(time.Second)
		fmt.Println(x)
	}
}
</code></pre>

<p>
</p>

</div>

<a class="anchor" id="range"></a>
<h3><code>for-range</code> on Channels</h3>

<div>
The <code>for-range</code> control flow code block applies to channels.
The loop will try to iteratively receive the values sent to a channel,
until the channel is closed and its value buffer queue becomes blank.
Unlike the <code>for-range</code> syntax on arrays, slices and maps,
most one iteration variable, which is used to store the received values,
is allowed to be present in the <code>for-range</code> syntax on channels.

<pre class="line-numbers"><code class="language-go">for v = range aChannel {
	// use v
}
</code></pre>

is equivalent to

<pre class="line-numbers"><code class="language-go">for {
	v, ok = <-aChannel
	if !ok {
		break
	}
	// use v
}
</code></pre>

<p>
Surely, here the <code>aChannel</code> value must not be a send-only channel.
If it is a nil channel, the loop will block there for ever.
</p>

For example, the second <code>for</code> loop block in the example
shown in the last section can be simplified to

<pre class="line-numbers"><code class="language-go">	for x := range c {
		time.Sleep(time.Second)
		fmt.Println(x)
	}
</code></pre>

<p>
</p>
</div>

<a class="anchor" id="select"></a>
<h3><code>select-case</code> Control Flow Code Blocks</h3>

<div>
There is a <code>select-case</code> code block syntax which is specially designed for channels.
The syntax is much like the <code>switch-case</code> block syntax.
For example, there can be multiple <code>case</code> branches and at most one
<code>default</code> branch in the <code>select-case</code> code block.
But there are also some obvious differences between them.
<ul>
<li>
	No expressions and statements are allowed to follow the <code>select</code> keyword
	(before <code>{</code>).
</li>
<li>
	No <code>fallthrough</code> statements are allowed to be used in <code>case</code> branches.
</li>
<li>
	Each statement following a <code>case</code> keyword in a <code>select-case</code> code block
	must be either a channel receive operation or a channel send operation statement.
	A channel receive operation can appear as the source value of a simple assignment statement.
	Later, a channel operation following a <code>case</code> keyword will be called a <code>case</code> operation.
</li>
<li>
	In case of there are some non-blocking <code>case</code> operations,
	Go runtime will <b>randomly select one of them to execute</b>,
	then continue to execute the corresponding <code>case</code> branch.
</li>
<li>
	In case of all the <code>case</code> operations
	in a <code>select-case</code> code block are blocking operations,
	the <code>default</code> branch will be selected to execute
	if the <code>default</code> branch is present.
	If the <code>default</code> branch is absent,
	the current goroutine will be pushed into the corresponding
	sending goroutine queue or receiving goroutine queue of
	every channel involved in all <code>case</code> operations,
	then enter blocking state.
</li>
</ul>

<p>
By the rules, a <code>select-case</code> code block without any branches,
<code>select{}</code>, will make the current goroutine stay in blocking state forever.
</p>

The following program will enter the <code>default</code> branch for sure.
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var c chan struct{} // nil
	select {
	case <-c:             // blocking operation
	case c <- struct{}{}: // blocking operation
	default:
		fmt.Println("Go here.")
	}
}
</code></pre>

<p>
</p>

An example showing how to use try-send and try-receive:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	c := make(chan string, 2)
	trySend := func(v string) {
		select {
		case c <- v:
		default: // go here if c is full.
		}
	}
	tryReceive := func() string {
		select {
		case v := <-c: return v
		default: return "-" // go here if c is empty
		}
	}
	trySend("Hello!") // succeed to send
	trySend("Hi!")    // succeed to send
	// Fail to send, but will not block.
	trySend("Bye!")
	// The following two lines will
	// both succeed to receive.
	fmt.Println(tryReceive()) // Hello!
	fmt.Println(tryReceive()) // Hi!
	// The following line fails to receive.
	fmt.Println(tryReceive()) // -
}
</code></pre>

<p>
</p>

The following example has 50% possibility to panic.
Both of the two <code>case</code> operations are non-blocking in this example.

<pre class="line-numbers"><code class="language-go">package main

func main() {
	c := make(chan struct{})
	close(c)
	select {
	case c <- struct{}{}:
		// Panic if the first case is selected.
	case <-c:
	}
}
</code></pre>


</div>

<a class="anchor" id="select-implementation"></a>
<h3>The Implementation of the Select Mechanism</h3>

<div>
<p>
The select mechanism in Go is an important and unique feature.
Here the steps of <a href="https://github.com/golang/go/blob/master/src/runtime/select.go">the
select mechanism implementation by the official Go runtime</a> are listed.
</p>

<!--
If the step ids change, please also update the above reference ones.
-->

There are several steps to execute a <code>select-case</code> block:
<ol>
<li>
	evaluate all involved channel expressions and value expressions to be potentially sent in <code>case</code> operations,
	from top to bottom and left to right.
	Destination values for receive operations (as source values) in assignments needn't to be evaluated at this time.
</li>
<li>
	randomize the branch orders for polling in step <i>5</i>.
	The <code>default</code> branch is always put at the last position in the result order.
	Channels may be duplicate in the <code>case</code> operations.
</li>
<li>
	sort all involved channels in the <code>case</code> operations to avoid deadlock in the next step.
	No duplicate channels stay in the first <code>N</code> channels of the sorted result,
	where <code>N</code> is the number of involved channels in the <code>case</code> operations.
	Below, the <b><i>channel lock order</i></b> is a concept for the first <code>N</code> channels in the sorted result.
</li>
<li>
	lock (a.k.a., acquire the locks of) all involved channels by the channel lock order produced in last step.
</li>
<li>
	poll each branch in the select block by the randomized order produced in step <i>2</i>:
	<ol>
	<li>
		if this is a <code>case</code> branch and
		the corresponding channel operation is a send-value-to-closed-channel operation,
		unlock all channels by the inverse channel lock order and make the current goroutine panic.
		Go to step <i>12</i>.
	</li>
	<li>
		if this is a <code>case</code> branch and
		the corresponding channel operation is non-blocking,
		perform the channel operation and unlock all channels by the inverse channel lock order,
		then execute the corresponding <code>case</code> branch body.
		The channel operation may wake up another goroutine in blocking state.
		Go to step <i>12</i>.
	</li>
	<li>
		if this is the <code>default</code> branch,
		then unlock all channels by the inverse channel lock order and execute the <code>default</code> branch body.
		Go to step <i>12</i>.
	</li>
	</ol>
	(Up to here, the <code>default</code> branch is absent and all <code>case</code> operations are blocking operations.)
</li>
<li>
	push (enqueue) the current goroutine (along with the information of the corresponding <code>case</code> branch)
	into the receiving or sending goroutine queue of the involved channel in each <code>case</code> operation.
	The current goroutine may be pushed into the queues of a channel for multiple times,
	for the involved channels in multiple cases may be the same one.
</li>
<li>
	make the current goroutine enter blocking state and unlock all channels by the inverse channel lock order.
</li>
<li>
	wait in blocking state until other channel operations wake up the current goroutine, ...
</li>
<li>
	the current goroutine is waken up by another channel operation in another goroutine.
	The other operation may be a channel close operation or a channel send/receive operation.
	If it is a channel send/receive operation,
	there must be a <code>case</code> channel receive/send operation
	(in the current being explained <code>select-case</code> block) cooperating with it (by transferring a value).
	In the cooperation, the current goroutine will be dequeued from the receiving/sending goroutine queue of the channel.
</li>
<li>
	lock all involved channels by the channel lock order.
</li>
<li>
	dequeue the current goroutine from the receiving goroutine queue or sending goroutine queue of the involved channel
	in each <code>case</code> operation,
	<ol>
	<li>
		if the current goroutine is waken up by a channel close operation, go to step <i>5</i>.
	</li>
	<li>
		if the current goroutine is waken up by a channel send/receive operation,
		the corresponding <code>case</code> branch of the cooperating receive/send operation
		has already been found in the dequeuing process,
		so just unlock all channels by the inverse channel lock order
		and execute the corresponding <code>case</code> branch.
	</li>
	</ol>
</li>
<li>
	done.
</li>
</ol>

From the implementation, we know that
<ul>
<li>
	a goroutine may stay in the sending goroutine queues and
	the receiving goroutine queues of multiple channels at the same time.
	It can even stay in the sending goroutine queue and the
	receiving goroutine queue of the same channel at the same time.
</li>
<li>
	when a goroutine being blocked at a <code>select-case</code> code block gets resumed later,
	it will be removed from all the sending goroutine queues
	and the receiving goroutine queues of every channels
	involved in the channel operations followed <code>case</code> keywords
	in the <code>select-case</code> code block.
</li>
</ul>

<p>
</p>

</div>

<h3>More</h3>

<p>
We can find more channel use cases in <a href="channel-use-cases.html">this article</a>.
</p>

<p>
Although channels can help us write
<a href="channel-closing.html">correct concurrent code easily</a>,
like other data synchronization techniques,
channels will not prevent us from
<a href="concurrent-common-mistakes.html">writing improper concurrent code</a>.
</p>

<p>
Channel may be not always the best solution for all use cases for data synchronizations.
Please read <a href="concurrent-synchronization-more.html">this article</a>
and <a href="concurrent-atomic-operation.html">this article</a>
for more synchronization techniques in Go.
</p>


